<template>
  <div class="JNPF-common-layout">
    <div class="JNPF-common-layout-center">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="4">
            <el-form-item>
              <el-input v-model="query.keyword" placeholder="订单编号/服务标题/服务机构" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-select v-model="query.paymentState" placeholder="订单状态" clearable>
                <el-option v-for="(item, index) in paymentStateOptions" :key="index" :label="item.fullName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-select v-model="query.payType" placeholder="支付方式" clearable>
                <el-option v-for="(item, index) in payTypeOptions" :key="index" :label="item.fullName" :value="item.enCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-date-picker
                v-model="query.creatorTime"
                value-format="timestamp"
                format="yyyy-MM-dd"
                start-placeholder="订单开始日期"
                end-placeholder="订单结束日期"
                type="daterange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="JNPF-common-layout-main JNPF-flex-main">
        <div class="JNPF-common-head">
          <div>
            <!-- <el-button type="primary" @click="addOrUpdateHandle()">新增</el-button> -->
          </div>
          <div class="JNPF-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh JNPF-common-head-icon" :underline="false" @click="reset()" />
            </el-tooltip>
          </div>
        </div>
        <JNPF-table v-loading="listLoading" :data="list" :span-method="arraySpanMethod" @sort-change="sortChange">
          <el-table-column prop="encode" label="订单编号" align="left" width="150" />
          <el-table-column prop="title" label="订单标题" align="left" />
          <el-table-column prop="amount" label="订单金额" align="left" />
          <el-table-column prop="vipLevelName" label="会员等级" align="left" />
          <el-table-column prop="vipPeriod" label="续费时长(月)" align="left" width="150" />
          <el-table-column prop="paymentState" label="支付状态" align="left">
            <template slot-scope="scope">
              {{ scope.row.paymentState == 0 ? '待支付' : scope.row.paymentState == 1 ?'已支付' : '取消支付' }}
            </template>
          </el-table-column>
          <el-table-column prop="approveState" label="审核状态" align="left" />
          <el-table-column prop="paymentstate_name" label="剩余支付时间" align="left" width="150">
            <template slot-scope="scope">
              <template v-if="scope.row.paymentState == 0">
                <count-down :endTime="scope.row.creatorTime + (3600000 * 24)" />
              </template>
              <template v-else>
                --
              </template>
              <!-- {{ scope.row.creatorTime }} -->
            </template>
          </el-table-column>
          <el-table-column prop="creatorTime" label="创建时间" align="left" width="150" :formatter="jnpf.tableDateFormat" />
          <el-table-column label="操作" fixed="right" width="150">
            <template slot-scope="scope">
              <el-button v-has="'btn_payment'" v-if="scope.row.paymentState == 0" type="text" @click="payCost(scope.row)">支付</el-button>
              <el-button v-has="'btn_cancel'" v-if="scope.row.paymentState == 0" type="text" @click="cancelPay(scope.row.id)">取消支付</el-button>
              <el-button v-has="'btn_contact'" v-if="scope.row.approveState == 2" type="text" @click="contact()">联系客服</el-button>
            </template>
          </el-table-column>
        </JNPF-table>
        <pagination
          :total="total"
          :page.sync="listQuery.currentPage"
          :limit.sync="listQuery.pageSize"
          @pagination="initData"
        />
      </div>
    </div>
    <JGOrder ref="order" :orderType="'members'" :visible.sync="orderVisible" :table-data="tableData" :active="stepsActive" @stepNext="stepNext" @dialogClose="dialogClose">
      <template #steps>
        <JGSteps :active="stepsActive" :steps="stepsList" />
      </template>
    </JGOrder>
    <jg-contact :visible.sync="contactVisible" />
  </div>
</template>

<script>
import request from '@/utils/request'
import columnList from './columnList'
import {vipOrderRecord, cancelPay} from '@/api/vip/order'
import {getDictionaryDataSelector } from '@/api/systemData/dictionary'

export default {
  // components: { JNPFForm, ExportBox, Detail },
  data() {
    return {
      expandObj: {},
      columnOptions: [],
      mergeList: [],
      exportList: [],
      columnList,

      detailVisible: false,
      query: {},
      treeProps: {
        children: 'children',
        label: 'fullName',
        value: 'id'
      },
      list: [],
      listLoading: true,
      total: 0,
      listQuery: {
        superQueryJson: '',
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: ''
      },
      formVisible: false,
      exportBoxVisible: false,
      paymentStateOptions: [{
        fullName: '待支付',
        id: 0
      }, {
        fullName: '已支付',
        id: 1
      }, {
        fullName: '已取消',
        id: 2
      }],
      payTypeOptions: [],
      orderVisible: false,
      tableData: [],
      stepsList: ['确认订单', '确认付款', '完成订购'],
      stepsActive: 1,
      contactVisible:false
    }
  },
  computed: {
    menuId() {
      return this.$route.meta.modelId || ''
    }
  },
  created() {
    this.getPayTypeOptions()
    this.getColumnList()
    this.initData()
  },
  methods: {
    getPayTypeOptions() {
      getDictionaryDataSelector('367299187424887877').then(res => {
        this.payTypeOptions = res.data.list
      })
    },
    getColumnList() {
      // 没有开启权限
      this.columnOptions = this.transformColumnList(this.columnList)
    },
    transformColumnList(columnList) {
      const list = []
      for (let i = 0; i < columnList.length; i++) {
        const e = columnList[i]
        if (!e.prop.includes('-')) {
          list.push(e)
        } else {
          const prop = e.prop.split('-')[0]
          const label = e.label.split('-')[0]
          const vModel = e.prop.split('-')[1]
          const newItem = {
            align: 'center',
            jnpfKey: 'table',
            prop,
            label,
            children: []
          }
          e.vModel = vModel
          if (!this.expandObj.hasOwnProperty(`${prop}Expand`)) this.$set(this.expandObj, `${prop}Expand`, false)
          if (!list.some(o => o.prop === prop)) list.push(newItem)
          for (let i = 0; i < list.length; i++) {
            if (list[i].prop === prop) {
              list[i].children.push(e)
              break
            }
          }
        }
      }
      this.getMergeList(list)
      this.getExportList(list)
      return list
    },
    arraySpanMethod({
      column
    }) {
      for (let i = 0; i < this.mergeList.length; i++) {
        if (column.property === this.mergeList[i].prop) {
          return [this.mergeList[i].rowspan, this.mergeList[i].colspan]
        }
      }
    },
    getMergeList(list) {
      const newList = JSON.parse(JSON.stringify(list))
      newList.forEach(item => {
        if (item.children && item.children.length) {
          const child = {
            prop: item.prop + '-child-first'
          }
          item.children.unshift(child)
        }
      })
      newList.forEach(item => {
        if (item.children && item.children.length) {
          item.children.forEach((child, index) => {
            if (index === 0) {
              this.mergeList.push({
                prop: child.prop,
                rowspan: 1,
                colspan: item.children.length
              })
            } else {
              this.mergeList.push({
                prop: child.prop,
                rowspan: 0,
                colspan: 0
              })
            }
          })
        } else {
          this.mergeList.push({
            prop: item.prop,
            rowspan: 1,
            colspan: 1
          })
        }
      })
    },
    getExportList(list) {
      const exportList = []
      for (let i = 0; i < list.length; i++) {
        if (list[i].jnpfKey === 'table') {
          for (let j = 0; j < list[i].children.length; j++) {
            exportList.push(list[i].children[j])
          }
        } else {
          exportList.push(list[i])
        }
      }
      this.exportList = exportList
    },
    goDetail(id) {
      this.detailVisible = true
      this.$nextTick(() => {
        this.$refs.Detail.init(id)
      })
    },
    sortChange({
      column,
      prop,
      order
    }) {
      this.listQuery.sort = order === 'ascending' ? 'asc' : 'desc'
      this.listQuery.sidx = !order ? '' : prop
      this.initData()
    },
    initData() {
      this.listLoading = true
      if (this.query.creatorTime) {
        this.query.startTime = this.query.creatorTime[0]
        this.query.endTime = this.query.creatorTime[1]
      }
      const _query = {
        ...this.listQuery,
        ...this.query,
        dataType: 0,
        menuId: this.menuId
      }
      request({
        url: `/api/vip/vipOrderRecord/getList`,
        method: 'post',
        data: _query
      }).then(res => {
        res.data.list = res.data.list ? res.data.list : []
        res.data.pagination = res.data.pagination ? res.data.pagination : {currentPage: 1,pageSize: 20,total: 0}
        var _list = []
        for (let i = 0; i < res.data.list.length; i++) {
          const _data = res.data.list[i]
          _list.push(_data)
        }
        this.list = _list.map(o => ({
          ...o,
          ...this.expandObj
        }))
        this.total = res.data.pagination.total
        this.listLoading = false
      })
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        request({
          url: `/api/vip/vipOrderRecord/${id}`,
          method: 'DELETE'
        }).then(res => {
          this.$message({
            type: 'success',
            message: res.msg,
            onClose: () => {
              this.initData()
            }
          })
        })
      }).catch(() => {})
    },
    addOrUpdateHandle(id, isDetail) {
      this.formVisible = true
      this.$nextTick(() => {
        this.$refs.JNPFForm.init(id, isDetail)
      })
    },
    exportData() {
      this.exportBoxVisible = true
      this.$nextTick(() => {
        this.$refs.ExportBox.init(this.exportList)
      })
    },
    download(data) {
      const query = {
        ...data,
        ...this.listQuery,
        ...this.query,
        menuId: this.menuId
      }
      request({
        url: `/api/vip/vipOrderRecord/Actions/Export`,
        method: 'post',
        data: query
      }).then(res => {
        if (!res.data.url) return
        this.jnpf.downloadFile(res.data.url)
        this.$refs.ExportBox.visible = false
        this.exportBoxVisible = false
      })
    },
    search() {
      this.listQuery.currentPage = 1
      this.listQuery.pageSize = 20
      this.listQuery.sort = 'desc'
      this.listQuery.sidx = ''
      this.initData()
    },
    refresh(isrRefresh) {
      this.formVisible = false
      if (isrRefresh) this.reset()
    },
    reset() {
      for (const key in this.query) {
        this.query[key] = undefined
      }
      this.search()
    },
    payCost(data) {
      this.$refs.order.payment(data, 'members')
      this.orderVisible = true
    },
    cancelPay(id) {
      const data = {
        paymentState: 2
      }
      this.$confirm('订单取消成功后将无法恢复，是否取消', '取消订单？', {
        confirmButtonText: '确定',
        cancelButtonText: '返回',
        type: 'warning'
      }).then(() => {
        cancelPay(id, data).then(res => {
          if (res.code === 200) {
            this.search()
          }
        })
      }).catch(() => {
      });
    },
    stepNext(val) {
      this.stepsActive = val
    },
    contact() {
      this.contactVisible = true
    },
    dialogClose() {
      this.search()
    }
  }
}
</script>
